package com.googlecode.openrtp.grizzly.util;

import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import org.glassfish.grizzly.Buffer;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.glassfish.grizzly.memory.CompositeBuffer;
import org.glassfish.grizzly.memory.MemoryUtils;

/**
 *
 * @author jocke
 */
@Singleton
public class BufferUtil implements Provider<Buffer> {

    public static final byte ZERO_BYTE = (byte) 0;

    public long getUnsignedIntAsLong(final Buffer sourceBuffer, ByteBuffer buffer) {
        sourceBuffer.get(buffer, 4, 4);
        long ts = buffer.getLong();
        buffer.clear();
        return ts;
    }

    public ByteBuffer allocate(FilterChainContext ctx, int length) {
        return MemoryUtils.allocateByteBuffer(ctx.getMemoryManager(), length);
    }

    public Buffer allocateBuffer(FilterChainContext ctx, int length) {
        return ctx.getMemoryManager().allocate(length);
    }

    public void release(FilterChainContext ctx, ByteBuffer buffer) {
        MemoryUtils.releaseByteBuffer(ctx.getMemoryManager(), buffer);
    }

    public String readString(Buffer buffer, int length) throws UnsupportedEncodingException {
        byte[] b = new byte[length];
        buffer.get(b);
        return new String(b, 0, b.length, "UTF-8");
    }

    public static String toBinaryString(byte n) {
        StringBuilder sb = new StringBuilder("00000000");
        for (int bit = 0; bit < 8; bit++) {
            if (((n >> bit) & 1) > 0) {
                sb.setCharAt(7 - bit, '1');
            }
        }
        return sb.toString();
    }

    public static String toBinaryString(Buffer buffer) {
        buffer.position(0);
        byte[] bits = new byte[buffer.remaining()];
        buffer.get(bits);
        StringBuilder sb = new StringBuilder();

        int c = 0;
        for (int i = 0; i < bits.length; i++) {
            c++;
            sb.append(toBinaryString(bits[i]));
            if (c == 4) {
                sb.append("\n");
                c = 0;
            }
        }
        return sb.toString();
    }

    public void paddingToBoundry(Buffer buffer) {
        while ((buffer.position()) % 4 != 0) {
            buffer.put(ZERO_BYTE);
        }
    }

    public void seekBoundry(Buffer buffer) {
        while ((buffer.position()) % 4 != 0) {
            buffer.get();
        }
    }

    @Override
    public Buffer get() {
        return CompositeBuffer.newBuffer();
    }
}
